package com.ybkj.daijia.server.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.config.RentApi;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Blazk.
 */
@RestController
@RequestMapping(value = "rentcar")
public class RentCarController {

    @Autowired
    private RentApi rentApi;

    @Autowired
    private SettingUtils settingUtils;

    /**
     * 添加车辆.
     *
     * @param name        车辆名称.
     * @param companyName 公司名称.
     * @param companyId   公司id.
     * @param shopId      门店id.
     * @param shopName    门店名称.
     * @param plateNo     车牌号.
     * @param mileage     已行驶流程.
     * @param limit       是否限行 0不限行 1-7对应星期.
     * @param purchase    购置时间.
     * @param vehicleId   车系id.
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentcar")) {

            ModelAndView mv = new ModelAndView();
            mv.setViewName("rentcar/list");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "update", method = RequestMethod.GET)
    public ModelAndView update(@RequestParam("id") Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentcar")) {

            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("id", id);
            modelAndView.setViewName("rentcar/update");
            return modelAndView;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentcar")) {

            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("rentcar/add");
            return modelAndView;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "insertCar", method = RequestMethod.POST)
    public Map<String, Object> insertRentshop(
        @RequestParam("name") String name,
        @RequestParam("companyName") String companyName,
        @RequestParam("companyId") Long companyId,
        @RequestParam("shopId") Long shopId,
        @RequestParam("shopName") String shopName,
        @RequestParam("plateNo") String plateNo,
        @RequestParam("mileage") Integer mileage,
        @RequestParam("limit") Integer limit,
        @RequestParam("purchase") Integer purchase,
        @RequestParam("vehicleId") Long vehicleId,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("name", name);
        kv.add("companyId", String.valueOf(companyId));
        kv.add("companyName", companyName);
        kv.add("shopId", String.valueOf(shopId));
        kv.add("shopName", shopName);
        kv.add("plateNo", plateNo);
        kv.add("limit", String.valueOf(limit));
        kv.add("mileage", String.valueOf(mileage));
        kv.add("purchase", String.valueOf(purchase));
        kv.add("vehicleId", String.valueOf(vehicleId));
        Gson gson = new Gson();
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.INSERT_CAR, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "车辆创建失败");
            map.put("success", true);
        } else {
            map.put("message", "车辆创建成功");
            map.put("success", false);
        }
        return map;
    }

    /**
     * 修改车辆.
     *
     * @param id          门店车辆id.
     * @param name        车辆名称.
     * @param companyName 公司名称.
     * @param companyId   公司id.
     * @param shopId      门店id.
     * @param shopName    门店名称.
     * @param plateNo     车牌号.
     * @param mileage     已行驶流程.
     * @param limit       是否限行 0不限行 1-7对应星期.
     * @param purchase    购置时间.
     * @param vehicleId   车系id.
     */
    @RequestMapping(value = "updateCar", method = RequestMethod.POST)
    public Map<String, Object> updateCar(
        @RequestParam("id") Long id,
        @RequestParam("name") String name,
        @RequestParam("companyName") String companyName,
        @RequestParam("companyId") Long companyId,
        @RequestParam("shopId") Long shopId,
        @RequestParam("shopName") String shopName,
        @RequestParam("plateNo") String plateNo,
        @RequestParam("mileage") Integer mileage,
        @RequestParam("limit") Integer limit,
        @RequestParam("purchase") Integer purchase,
        @RequestParam("vehicleId") Long vehicleId,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("id", String.valueOf(id));
        kv.add("name", name);
        kv.add("companyId", String.valueOf(companyId));
        kv.add("companyName", companyName);
        kv.add("shopId", String.valueOf(shopId));
        kv.add("shopName", shopName);
        kv.add("plateNo", plateNo);
        kv.add("limit", String.valueOf(limit));
        kv.add("mileage", String.valueOf(mileage));
        kv.add("purchase", String.valueOf(purchase));
        kv.add("vehicleId", String.valueOf(vehicleId));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.UPDATE_CAR, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "车辆修改成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "updateGrounding", method = RequestMethod.POST)
    public Map<String, Object> updateCar(
        @RequestParam("id") Long id,
        @RequestParam("isGrounding") Integer isGrounding,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("id", String.valueOf(id));
        kv.add("isGrounding", String.valueOf(isGrounding));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.GROUNDING_CAR, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            if (isGrounding == 0) {
                map.put("message", "车辆下架成功");
                map.put("success", true);
            } else {
                map.put("message", "车辆上架成功");
                map.put("success", true);
            }

        } else {
            if (isGrounding == 0) {
                map.put("message", "车辆下架失败");
                map.put("success", false);
            } else {
                map.put("message", "车辆上架失败");
                map.put("success", true);
            }
        }
        return map;
    }

    /**
     * 查询门店车辆.
     *
     * @param id 门店车辆id.
     */
    @RequestMapping(value = "findById", method = RequestMethod.GET)
    public Map<String, Object> findById(@RequestParam("id") Long id,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(RentApi.SELECT_CAR_BYID)
            .append("?appkey={appkey}");
        if (null != id) {
            kv.put("id", String.valueOf(id));
            builder.append("&id={id}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        Map<String, Object> map = new HashMap<String, Object>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                String dataString = data.toString();
                map.put("success", true);
                map.put("data", dataString);
            } else {
                map.put("success", false);
                map.put("message", jo.getString("message"));
            }
        }
        return map;
    }

    /**
     * 查询车辆.
     *
     * @param shopId      Long 门店id.
     * @param isGrounding Integer '0上架1下架.
     * @param param       String 车牌号.
     * @param rows
     * @param page
     * @return
     */
    @RequestMapping(value = "findCar", method = RequestMethod.GET)
    public Page<Map<String, Object>> findCar(
        @RequestParam(required = false, value = "shopId") Long shopId,
        @RequestParam(required = false, value = "vehicleId") Long vehicleId,
        @RequestParam(required = false, value = "isGrounding") Integer isGrounding,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "state") Integer state,
        @RequestParam(required = false, value = "rows") Integer rows,
        @RequestParam(required = false, value = "page") Integer page,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(RentApi.SELECT_CAR)
            .append("?appkey={appkey}");
        if (null != shopId) {
            kv.put("shopId", String.valueOf(shopId));
            builder.append("&shopId={shopId}");
        }
        if (null != vehicleId) {
            kv.put("vehicleId", String.valueOf(vehicleId));
            builder.append("&vehicleId={vehicleId}");
        }
        if (null != param) {
            kv.put("param", param);
            builder.append("&param={param}");
        }
        if (null != isGrounding) {
            kv.put("isGrounding", String.valueOf(isGrounding));
            builder.append("&isGrounding={isGrounding}");
        }
        if (null != state) {
            kv.put("state", String.valueOf(state));
            builder.append("&state={state}");
        }
        page = Pager.getPage();
        rows = Pager.getLimit();
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        List<Map<String, Object>> cars = new ArrayList<Map<String, Object>>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray jsonArray = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                cars = gson
                    .fromJson(jsonArray.toString(), new TypeToken<List<Map<String, Object>>>() {
                    }.getType());
            }
        }
        return new PageImpl<Map<String, Object>>(cars, pageable, total);
    }

    /***
     * 修改车辆状态.
     * @param id 门店车辆id.
     * @param state 状态 0空闲 1忙碌.
     */
    @RequestMapping(value = "updateCarStatus", method = RequestMethod.POST)
    public Map<String, Object> updateCarStatus(
        @RequestParam("id") Long id,
        @RequestParam("state") Integer state) {

        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("id", String.valueOf(id));
        kv.add("state", String.valueOf(state));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.UPDATE_CAR_STATE, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "车辆状态修改成功");
            map.put("success", true);

        } else {
            map.put("message", "车辆状态修改失败");
            map.put("success", true);
        }
        return map;
    }

    /**
     * 查询车辆.
     *
     * @param brandId Long 品牌id.
     * @param plateNo String 车牌号.
     * @param rows
     * @param page
     * @return
     */
    @RequestMapping(value = "findByBrandIdAndPlateNo", method = RequestMethod.GET)
    public Page<Map<String, Object>> findByBrandIdAndPlateNo(
        @RequestParam(required = false, value = "brandId") Long brandId,
        @RequestParam(required = false, value = "typeId") Long typeId,
        @RequestParam(required = false, value = "shopId") Long shopId,
        @RequestParam(required = false, value = "plateNo") String plateNo,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "rows") Integer rows,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(RentApi.SELECT_CAR_BRANDIDANDPALTENO)
            .append("?appkey={appkey}");
        if (null != plateNo) {
            kv.put("plateNo", plateNo);
            builder.append("&plateNo={plateNo}");
        }
        if (null != brandId) {
            kv.put("brandId", String.valueOf(brandId));
            builder.append("&brandId={brandId}");
        }
        if (null != shopId) {
            kv.put("shopId", String.valueOf(shopId));
            builder.append("&shopId={shopId}");
        }
        if (null != typeId) {
            kv.put("typeId", String.valueOf(typeId));
            builder.append("&typeId={typeId}");
        }
        page = Pager.getPage();
        rows = Pager.getLimit();
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        List<Map<String, Object>> cars = new ArrayList<Map<String, Object>>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray jsonArray = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                cars = gson
                    .fromJson(jsonArray.toString(), new TypeToken<List<Map<String, Object>>>() {
                    }.getType());
            }
        }
        return new PageImpl<Map<String, Object>>(cars, pageable, total);
    }

    @RequestMapping(value = "findByshopIdAndVehicleId", method = RequestMethod.GET)
    public Page<Map<String, Object>> findByshopIdAndVehicleId(
        @RequestParam(required = false, value = "shopId") Long shopId,
        @RequestParam(required = false, value = "vehicleId") Long vehicleId,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(RentApi.SELECT_CAR_VEHICLEID)
            .append("?appkey={appkey}");
        if (null != shopId) {
            kv.put("shopId", String.valueOf(shopId));
            builder.append("&shopId={shopId}");
        }
        if (null != vehicleId) {
            kv.put("vehicleId", String.valueOf(vehicleId));
            builder.append("&vehicleId={vehicleId}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        List<Map<String, Object>> cars = new ArrayList<Map<String, Object>>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray jsonArray = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                cars = gson
                    .fromJson(jsonArray.toString(), new TypeToken<List<Map<String, Object>>>() {
                    }.getType());
            }
        }
        return new PageImpl<Map<String, Object>>(cars, pageable, total);
    }


}
